<template>
  <div class="dt-page-box">
    <div class="dt-content-head">
      <div class="dt-content-head-tab">
        <div class="dt-head-title">
          <div class="dt-head-breadcrumb" @click="goBack">
            <i class="el-icon-arrow-left"></i>
            <span>返回</span>
            <em>|</em>
          </div>
          <!-- <span>项目</span> -->
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item v-for="(item,index) in crumbList" :key="item.id">
              <template v-if="(crumbList.length-1)==index">
                {{item.name}}
              </template>
              <a v-else-if="index==0" @click.stop.prevent="goBreadcrumb(item,1)">{{item.name}}</a>
              <a v-else @click.stop.prevent="goBreadcrumb(item)">{{item.name}}</a>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="dt-head-search">
          <el-input placeholder="请输入创建人/文件名" v-model.trim="keywords" size="mini" @keyup.enter="handleSearch" clearable @clear="handleSearch">
            <el-button slot="append" @click="handleSearch">搜索</el-button>
          </el-input>
        </div>
      </div>
    </div>
    <div class="dt-content-page">
      <div class="custom-table" :class="{ 'empty': tableData.length==0}">
        <PublicEmpty v-if="tableData.length==0" :ishowImage="true" />
        <el-table v-else :data="tableData" style="width: 100%" @row-click="goDetail" :row-class-name="tableRowClassName">
          <el-table-column prop="folderName" label="名称" min-width="650px">
            <template slot-scope="scope">
              <div class="dt-table-item">
                <!-- <i class="dt-icon dt-icon-file"></i> -->
                <!-- <i :class="'dt-icon dt-icon-'+'video'"></i> -->
                <i v-if="scope.row.folderType!=6" class="dt-icon dt-icon-file"></i>
                <i v-else-if="scope.row.fileType==1" class="dt-icon dt-icon-pic"></i>
                <i v-else :class="'dt-icon dt-icon-'+$tools.fileTypeName(scope.row.fileSuffix)"></i>
                <!-- {{scope.row.folderName||'--'}} -->
                <span v-html="highlighted(scope.row.folderName)"></span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createName" label="创建人" min-width="180px">
            <template slot-scope="scope">
              <div>{{scope.row.createName||'--'}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="时间" min-width="320px">
            <template slot-scope="scope">
              <div>{{scope.row.updateTime||scope.row.createTime||'--'}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" label="大小" min-width="180px">
            <template slot-scope="scope">
              <div v-if="scope.row.fileSize">{{scope.row.fileSize|formatBytes}}</div>
              <div v-else>--</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <div v-if="scope.row.fileSize">
                <el-link v-if="scope.row.folderType==6" type="primary" :href="$tools.getStsFileUrl(secret_uid,scope.row.fileUrl)"
                  target="_blank">下载</el-link>
                <el-button v-else type="text" :loading="scope.row.downLoadLock"
                  @click.stop.prevent="downloadFile(scope.row,scope.$index)">下载</el-button>
              </div>
              <div v-else>--</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="public-page" v-if="totalRecord>19">
        <el-pagination class="pagination" v-if="totalRecord > 19" :current-page="page" :page-size="19" :total="totalRecord"
          layout="total, prev, pager, next, jumper" @current-change="handlePageChange">
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      secret_uid: this.$store.state.uid,
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      loading: { mounted: false },
      tableData: [],
      activeName: '3',
      currentGroupInfo: {},
      currentProjectId: this.$tools.getQuery(this).rootProjectId,
      keywords: '',
      page: parseInt(this.$route.query.page || 1),
      totalRecord: 0,
      crumbList: []
    }
  },
  computed: {
    tabs() {
      return this.$tools.getTabs(this, this.secret_uid)
    },
    elTab() {
      return this.$tools.getQuery(this).elTab || '0'
    },
    query() {
      return this.$tools.getQuery(this)
    },
    rootProjectId() {
      return this.$tools.getQuery(this).rootProjectId
    }
  },
  filters: {
    formatBytes(bytes, decimals = 2) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const dm = decimals < 0 ? 0 : decimals
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
    }
  },
  methods: {
    changeTab(tab, event) {
      var data = { elTab: tab.index, rootProjectId: this.query.rootProjectId }
      this.$router.push('/main/#/pm?tab=detail&' + this.$qs.stringify(data))
    },
    elTabChange(elTab) {
      this.activeName = elTab.split('-')[0]
      //this.subActiveName = elTab.split('-')[1]
    },
    goBreadcrumb(item, isData) {
      var data = {}
      if (isData) {
        data = { elTab: '3', rootProjectId: this.query.rootProjectId }
      } else {
        data = { elTab: '3-0', rootProjectId: this.query.rootProjectId, folderId: item.id }
      }
      this.keywords = ''
      this.$router.push('/main/#/pm?tab=detail&' + this.$qs.stringify(data))
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.folderType != 6) {
        return ' '
      } else {
        return 'dt-default'
      }
    },
    goDetail(row, column, event) {
      var data = { elTab: '3-0', rootProjectId: this.query.rootProjectId, folderId: row.id }
      if (row.folderType != 6) {
        this.$router.push('/main/#/pm?tab=detail&' + this.$qs.stringify(data))
      }
    },
    showCard() {
      this.dataCard.isShowCard = true
    },
    goBack() {
      // switch (this.elTab) {
      //   case '0':
      //   case '1':
      //   case '2':
      //   case '3':
      //   case '4':
      //     this.$router.push('/main/#/pm?tab=list&elTab=0')
      //     break
      //   case '0-0':
      //     this.$router.push('/main/#/pm?tab=detail&elTab=0&rootProjectId=' + this.query.rootProjectId)
      //     break
      //   case '2-0':
      //     this.$router.push('/main/#/pm?tab=detail&elTab=2&rootProjectId=' + this.query.rootProjectId)
      //     break
      //   case '3-0':
      //     this.$router.push('/main/#/pm?tab=detail&elTab=3&rootProjectId=' + this.query.rootProjectId)
      //     break
      // }
      this.$router.go(-1)
    },
    handleSearch() {
      this.groupFolderList()
    },
    handlePageChange(val) {
      this.page = val
      this.groupFolderList()
    },
    groupFolderList() {
      var data = [
          {
            userId: this.uid,
            folderId: this.query.folderId,
            // rootProjectId: this.query.rootProjectId,
            keywords: this.keywords,
            page: this.page,
            pageSize: 19
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/cloud/subFileList'],
        // path = ['/project/cloud/fileList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.crumbList = data.data.crumbList
              this.tableData = data.data.items.map((item) => {
                return {
                  ...item,
                  downLoadLock: false
                }
              })
              this.totalRecord = data.data.total_record
            } else {
              this.nodeList = []
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    downloadFile(row, index) {
      let item = row
      item.downLoadLock = true
      this.tableData.splice(index, 1, item)

      var data = [
          {
            userId: this.uid,
            folderId: row.id
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/cloud/download'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              // window.open('https://www.ccccdt.com' + data.data)
              location.href = this.$tools.getStsFileUrl(this.secret_uid, this.$store.state.DOMAIN + '/chat' + data.data)

              item.downLoadLock = false
              this.tableData.splice(index, 1, item)
            } else {
              this.nodeList = []
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    currentGroup(item) {
      this.currentGroupInfo = item
    },
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    },
    highlighted(str) {
      if (this.keywords) {
        let regex = new RegExp(`(${this.escapeRegExp(this.keywords)})`, 'gi')
        return str.replace(regex, '<span style="color:#f5222d">$1</span>')
      } else {
        return str
      }
    }
  },
  mounted() {
    if (this.query.folderId) {
      this.groupFolderList()
    }
  },
  watch: {
    $route(to, from) {
      // 对路由变化做出响应...
      // this.fetchData(to.params.id)
      if (this.query.folderId) {
        this.groupFolderList()
      }
    }
  }
}
</script>
<style scoped>
.dt-page-box {
  display: flex;
  flex-direction: column;
  flex: 1;
}
.dt-content-head-tab {
  height: 50px;
  line-height: 50px;
}
.dt-head-search >>> .el-input-group__append {
  background-color: #f0f5ff;
}
.dt-head-search >>> .el-button {
  color: #2f54eb;
  background-color: #f0f5ff;
  padding: 0px 20px;
}
.el-breadcrumb {
  line-height: 50px;
}

.dt-content-head-query {
  background: #fff;
}
.dt-content-page {
  padding: 14px;
}

.custom-table {
  /* padding: 14px; */
  background-color: #fff;

  flex: 1;
}
.custom-table.empty {
  display: flex;
  justify-content: center;
}
.dt-content-page >>> .el-table th.el-table__cell.is-leaf {
  border-bottom: none;
  /* color: #909399; */
}
.dt-table-item {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  /* cursor: pointer; */
}
.el-table >>> .el-table__body .dt-default {
  cursor: default;
}
.custom-table >>> .el-table th.el-table__cell > .cell {
  color: #909399;
  font-weight: normal;
}
.custom-table >>> .el-table .el-table__cell {
  padding: 8.5px 0px;
  line-height: 32px;
  color: #1f1f1f;
}
.custom-table >>> .el-table th.el-table__cell {
  padding: 4px 0px;
}
.dt-icon {
  margin-right: 8px;
  display: inline-block;
  width: 32px;
  height: 32px;
}
.dt-icon-word {
  background: url(/skb/img/projectData/ic_file-word32.png) no-repeat center bottom;
}
.dt-icon-excle {
  background: url(/skb/img/projectData/ic_file-excle32.png) no-repeat center bottom;
}
.dt-icon-pdf {
  background: url(/skb/img/projectData/ic_file-pdf32.png) no-repeat center bottom;
}
.dt-icon-ppt {
  background: url(/skb/img/projectData/ic_file-ppt32.png) no-repeat center bottom;
}
.dt-icon-txt {
  background: url(/skb/img/projectData/ic_file-txt32.png) no-repeat center bottom;
}
.dt-icon-video {
  background: url(/skb/img/projectData/ic_file-video32.png) no-repeat center bottom;
}
.dt-icon-zip {
  background: url(/skb/img/projectData/ic_file-zip32.png) no-repeat center bottom;
}
.dt-icon-pic {
  background: url(/skb/img/projectData/ic_file-pic32.png) no-repeat center bottom;
}
.dt-icon-file {
  background: url(/skb/img/projectData/ic_file32.png) no-repeat center bottom;
}
.dt-icon-unknown {
  background: url(/skb/img/projectData/ic_file-unknown32.png) no-repeat center bottom;
}

.dt-table-item {
  line-height: 32px;
}
.custom-table >>> .el-button {
  padding: 0px;
}
.pagination {
  padding: 20px 0px 40px;
  text-align: center;
}
</style>